package com.lf.controller;

import com.lf.dao.UserDao;
import com.lf.service.AuthCodeService;
import com.lf.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/code")
public class AuthCodeController {

    @Reference
    private AuthCodeService authCodeService;
    @Reference
    private EmailService emailService;
    @Autowired
    private UserDao userDao;


    // ⽣成验证码并发送到对应邮箱，成功true，失败false
    @GetMapping("/create/{email}")
    // 1、成功 2、请输入正确格式的邮箱 3、该邮箱已经注册过
    public Integer generateCodeAndSendToEmail(@PathVariable("email") String email) {

        // 使用正则表达式验证邮箱地址的有效性
        String regStr = "^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$";
        Pattern p = Pattern.compile(regStr);
        Matcher m = p.matcher(email);

        if(m.matches()) {
            // 检查该邮箱是否注册过
            if(userDao.findOneByEmail(email) != null) {
                return 3;
            } else {
                String code = authCodeService.generateCode(email);
                // 新开一个线程发邮件，避免超时
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        emailService.sendEmail(email,code);
                    }
                }).start();
                return 1;
            }
        } else {
            return 2;
        }
    }

    // 校验验证码是否正确，0正确1错误2超时
    @GetMapping("/validate/{email}/{code}")
    public Integer checkEmailAndCode(@PathVariable("email") String email,@PathVariable("code") String code) {
        return authCodeService.checkEmailAndCode(email,code);
    }



}
